// utils/request.js
import {
    baseUrl
} from '../config/config.js'

const config = {
    timeout: 10000,
    retryCount: 1,
    needLoading: true
}
//内存级，冷启动会自动失效 token
const requestInterceptor = (options) => {
    if (options.needLoading) wx.showLoading({
        title: '加载中',
        mask: true
    })
    //增强请求拦截器逻辑增加本地 token获取
    // 优先从 globalData 获取，失败则从 Storage 读取
    let token = getApp().globalData.token;
    if (!token) {
        try {
            const userInfo = wx.getStorageSync('userInfo');
            token = userInfo?.token || '';
            // 回填到 globalData 避免重复读取
            if (token) getApp().globalData.token = token;
        } catch (error) {
            console.error('读取存储失败:', error);
        }
    }

    options.header = {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
        ...options.header
    }
    return options
}



const responseInterceptor = (response, options) => {
    if (options.needLoading) wx.hideLoading()
    const {
        statusCode,
        data
    } = response
    if (statusCode === 401) wx.navigateTo({
        url: '/pages/login/login'
    })
    if (statusCode < 200 || statusCode >= 300) {
        const errorMsg = data?.message || `请求失败，状态码：${statusCode}`
        return Promise.reject(new Error(errorMsg))
    }
    return data
}

const request = (path, method = 'GET', data = {}, customConfig = {}) => {
    const options = {
        method,
        ...config,
        ...customConfig,
        header: customConfig.header || {}
    }
    const processedOptions = requestInterceptor(options)
    return new Promise((resolve, reject) => {
        let retry = 0
        const executeRequest = () => {
            const task = wx.request({
                url: `${baseUrl}${path}`,
                method: processedOptions.method,
                data,
                header: processedOptions.header,
                timeout: processedOptions.timeout,
                success: (res) => {
                    try {
                        const result = responseInterceptor(res, processedOptions)
                        resolve(result)
                    } catch (err) {
                        reject(err)
                    }
                },
                fail: (err) => {
                    if (retry < processedOptions.retryCount) {
                        retry++
                        executeRequest()
                    } else {
                        wx.hideLoading()
                        reject(new Error(`网络连接失败: ${err.errMsg}`))
                    }
                }
            })
            processedOptions.abort = () => task.abort()
        }
        executeRequest()
    })
}


// ✅ 正确导出快捷方法对象
const http = {
    get: (path, params, config) => request(path, 'GET', params, config),
    post: (path, data, config) => request(path, 'POST', data, config),
    put: (path, data, config) => request(path, 'PUT', data, config),
    delete: (path, data, config) => request(path, 'DELETE', data, config),
    patch: (path, data, config) => request(path, 'PATCH', data, config)
}

export default http


// 扩展文件上传方法
http.uploadFile = (path, filePath, formDataName, config = {}) => {
    return new Promise((resolve, reject) => {
        const options = requestInterceptor({
            ...config,
            needLoading: config.needLoading !== false
        })

        const uploadTask = wx.uploadFile({
            url: `${baseUrl}${path}`,
            filePath: filePath,
            name: formDataName,
            formData: config.formData || {},
            header: options.header,
            success: (res) => {
                try {
                    const data = JSON.parse(res.data)
                    const result = responseInterceptor({
                        statusCode: res.statusCode,
                        data: data
                    }, options)
                    resolve(result)
                } catch (e) {
                    reject(new Error('响应解析失败'))
                }
            },
            fail: (err) => {
                reject(new Error(`上传失败: ${err.errMsg}`))
            }
        })

        // 支持中止请求
        options.abort = () => uploadTask.abort()
    })
}